import 'package:flutter/material.dart';
import 'package:jtsell_app/entity/cart_item_entity.dart';

class CartListModel extends ChangeNotifier {
  List<CartItemEntity> items;

  CartListModel() {
    items = List();

    CartItemEntity.getAllList().then((list) {
      _setItemsList(list);
    });
  }

  _setItemsList(List<CartItemEntity> itemList) {
    items = itemList;
    notifyListeners();
  }

  ///
  /// 购物车总数量
  ///
  get itemsCount {
    return this.items.length;
  }

  ///
  /// 是否是全选
  ///
  bool get isAllchecked {
    return items.every((i) => i.isSelected);
  }

  ///
  /// 切换全选状态
  ///
  switchAllCheck() {
    if (this.isAllchecked) {
      items.forEach((i) => i.isSelected = false);
    } else {
      items.forEach((i) => i.isSelected = true);
    }
    notifyListeners();
  }

  ///
  /// 统计总数
  ///
  double get sumTotal {
    double total = 0;
    items.forEach((item) {
      if (item.isDeleted == false && item.isSelected == true) {
        total = item.price * item.buyCount + total;
      }
    });
    return total;
  }

  addItem(CartItemEntity entity) {
    ///判断当前的列表是不是包含当前商品
    ///
    int length = items.length;
    for (int i = 0; i < length; i++) {
      CartItemEntity item = items[i];
      if (item.productID == entity.productID) {
        addCount(i);

        return;
      }
    }

    ///如果不包含则加入到列表中
    items.add(entity);
    entity.save();

    CartItemEntity.getAllList().then((list) {
      list.forEach((item) {
        print(item.productName);
      });
    });

    notifyListeners();
  }

  ///
  /// 购物车+1
  ///
  addCount(int index) {
    CartItemEntity entity = items[index];
    entity.buyCount += 1;

    entity.updateBuyCount();

    notifyListeners();
  }

  ///
  /// 购物车-1
  ///
  downCount(int index) {
    CartItemEntity entity = items[index];
    entity.buyCount -= 1;

    entity.updateBuyCount();

    notifyListeners();
  }

  ///
  /// 滑动删除
  ///
  removeItem(index) {
    CartItemEntity entity = items[index];
    entity.delete().then((count){
      if(count>0){
        items.removeAt(index);
        notifyListeners();
      }
    });
  }

  ///
  /// 切换选择状态
  ///
  switchSelect(i) {
    items[i].isSelected = !items[i].isSelected;
    notifyListeners();
  }

  ///
  /// 购物车总数
  ///
  get totalCount {
    int count = 0;
    items.forEach((item) {
      if (item.isDeleted == false && item.isSelected == true) {
        count = item.buyCount + count;
      }
    });
    return count;
  }
}

final CartListModel cartListModel = CartListModel();
